const { app, BrowserWindow } = require('electron')
const puppeteer = require('puppeteer-core')
const path = require('path')
require('./ipc')


// 单实例锁
const gotTheLock = app.requestSingleInstanceLock()
if (!gotTheLock) {
  app.quit()
} else {
  console.log('正在设置远程调试端口...')
  app.commandLine.appendSwitch('remote-debugging-port', '9222')
  app.commandLine.appendSwitch('ignore-certificate-errors')
  // 添加更多调试相关的开关
  app.commandLine.appendSwitch('disable-features', 'OutOfBlinkCors')
  app.commandLine.appendSwitch('disable-site-isolation-trials')

  function createWindow() {
    const mainWindow = new BrowserWindow({
      // width: 1440,
      width: 1920,
      height: 850,
      webPreferences: {
        contextIsolation: true,
        nodeIntegration: false,
        webviewTag: true,
        webSecurity: false,
        preload: path.join(__dirname, 'preload/index.js')
      }
    })
  
    if (!app.isPackaged) {
      mainWindow.loadURL('http://localhost:5173')
    } else {
      mainWindow.loadFile(path.join(__dirname, '../dist/index.html'))
    }

    setTimeout(() => {
      if (!app.isPackaged) {
          mainWindow.webContents.openDevTools({mode: 'undocked'}) //打开调试窗口11
      }
    }, 1000)
  
    // 添加窗口加载完成的监听
    mainWindow.webContents.on('did-finish-load', async () => {
      console.log('窗口加载完成，检查调试端口...')
      // 验证调试端口是否可用
      fetch('http://localhost:9222/json/version')
        .then(response => response.json())
        .then(data => {
          console.log('调试端口已就绪:', data)
        })
        .catch(error => {
          console.error('调试端口检查失败:', error)
        })
      const browser = await puppeteer.connect({
          browserURL: 'http://localhost:9222',
          defaultViewport: null,
          ignoreHTTPSErrors: true
      })
      if (browser) {
          console.log("================= puppeteer:连接成功 ==================");
          // 将它挂到app下
          app.puppeteer = browser
      }
    })
  
    return mainWindow
  }

  // 确保应用完全准备好再创建窗口
  // let mainWindow = null
  app.whenReady().then(() => {
    console.log('应用准备就绪，创建主窗口...')
    app.mainWindow = createWindow()
  })

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      app.mainWindow = createWindow()
    }
  })

  app.on('window-all-closed', () => {
    if (process.platform !== 'darwin') {
      app.quit()
    }
  })
}




